package mark.tom.pistols.algorithm.encryption;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public final class AESEncryption {

    public static String encrypt(String key, String data) throws Exception {
        SecretKeySpec sKey = new SecretKeySpec(asBin(key), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sKey);
        return asHex(cipher.doFinal(data.getBytes()));
    }

    public static String decrypt(String key, String data) throws Exception {
        SecretKeySpec sKey = new SecretKeySpec(asBin(key), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sKey);
        return new String(cipher.doFinal(asBin(data)));
    }

    private static byte[] asBin(String src) {
        if (src.length() < 1) {
            return null;
        }
        byte[] encrypted = new byte[src.length() / 2];
        for (int i = 0; i < src.length() / 2; i++) {
            int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);
            encrypted[i] = (byte) (high * 16 + low);
        }
        return encrypted;
    }

    private static String asHex(byte buf[]) {
        StringBuilder sb = new StringBuilder(buf.length * 2);
        for (byte aBuf : buf) {
            if (((int) aBuf & 0xff) < 0x10) {
                sb.append("0");
            }
            sb.append(Long.toString((int) aBuf & 0xff, 16));
        }
        return sb.toString();
    }
}
